package org.dba.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dba.beanunit.BuildSQLUnit;
import org.dba.exception.ProcessException;
import org.dba.util.CommonProcessFile;

public class CoreService extends CommonProcessFile {

	Log log = LogFactory.getLog(getClass());

	private LinkedList<BuildSQLUnit> queue;
	private static CoreService instance = new CoreService();;

	public static synchronized CoreService getInstance() {
		return instance;
	}

	public CoreService() {
		new MakefileThread().start();
	}

	public void addQueue(BuildSQLUnit data) {
		synchronized (queue) {
			if (data != null || !"".equals(data)) {
				queue.addLast(data);
				if (data.getFlag().equals("--END")) {
					queue.notifyAll();
				}
			}
		}
	}

	public BuildSQLUnit getFirstQueue() {
		synchronized (queue) {
			if (queue.size() > 0)
				return queue.removeFirst();
			return null;
		}
	}

	public BuildSQLUnit getLastQueue() {
		synchronized (queue) {
			if (queue.size() > 0)
				return queue.removeLast();
			return null;
		}
	}

	class MakefileThread extends Thread {

		public MakefileThread() {
			super("makefilethread");
		}

		public void run() {
			log.info("核心处理线程已启动...");
			queue = new LinkedList<BuildSQLUnit>();
			while (true) {
				BuildSQLUnit lq = getLastQueue();
				if (lq != null) {
					if (lq.getFlag().equals("--END")) {
						// 如果最后的一行数据等于"END";说明已经处理完毕

						/*
						 * 加入发布信息
						 */
						makeDeployInfo();
						makefile(queue);
						if (queue != null) {
							queue = null;
							queue = new LinkedList<BuildSQLUnit>();
						}
					}
				} else {
					synchronized (queue) {
						try {
							queue.wait();
						} catch (InterruptedException e) {
						}
					}
				}
			}
		}
	}

	@Override
	public List<String> load2Mem(String filePath) throws ProcessException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<String> load2Mem(File[] filelist) throws ProcessException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean compareFile(List<String> sflist, List<String> tglist) throws ProcessException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean compareFile(String svalue, String opCode) throws ProcessException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void makefile(LinkedList<BuildSQLUnit> queue) throws ProcessException {
		OutputStreamWriter os = null;
		try {
			File file = new File(filePath + "compare-result.sql");
			if (file.exists()) {
				file.delete();
				file = new File(file.getAbsolutePath());
			}
			if (fileEncode == null) {
				os = new OutputStreamWriter(new FileOutputStream(file));
			} else {
				os = new OutputStreamWriter(new FileOutputStream(file), fileEncode);
			}
			try {
				for (BuildSQLUnit bsu : queue) {
					os.write(bsu.getSql() + System.getProperty("line.separator"));
				}
				os.flush();
			} finally {
				os.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void makeDeployInfo() {
		synchronized (queue) {
			StringBuffer hearderInfo = null, bottomInfo = null;
			BuildSQLUnit headerbsu, bottombsu;
			try {

				hearderInfo = new StringBuffer();
				bottomInfo = new StringBuffer();
				hearderInfo.append("-- ------------------------------------ -- \n");
				hearderInfo.append("-- 发布机构：北京久远银海软件股份有限公司 -- \n");
				hearderInfo.append("-- 发布日期：" + getDateTime(System.currentTimeMillis()) + " -- \n");
				hearderInfo.append("-- 版权所有 Copyright 北京久远银海软件股份有限公司 © 2012 V1.0 -- \n");
				hearderInfo.append("-- ------------------------------------ -- \n");
				bottomInfo.append("-- ------------------------------------ -- \n");
				bottomInfo.append("-- 成功结束! -- \n");
				bottomInfo.append("-- ------------------------------------ -- \n");
				headerbsu = new BuildSQLUnit();
				headerbsu.setFlag("INCOMING");
				headerbsu.setSql(hearderInfo.toString());
				bottombsu = new BuildSQLUnit();
				bottombsu.setFlag("INCOMING");
				bottombsu.setSql(bottomInfo.toString());
				queue.addFirst(headerbsu);
				queue.addLast(bottombsu);

			} finally {
				hearderInfo = null;
				bottomInfo = null;
				headerbsu = null;
				bottombsu = null;
			}
		}
	}

	public static String getDateTime(long millis) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dataTime = sdf.format(millis);
		return dataTime;
	}

	@Override
	public void buildFile(String filepath) throws ProcessException {
		// TODO Auto-generated method stub
		
	}

}
